# include <stdio.h>
# include <string.h>
# include "Header.h"
# include "DirectoryOps.h"
# include "vfs_errorcodes.h"
# include "NArrayTree.h"
# include "BinarySearchTree.h"
# include "Hashing.h"

int addFile(char *dirPath, char *fileName, char *data, struct VFS *header, struct NArray_node *NArrayRoot, struct BST_node *BSTRoot, struct HashNode **table) {
	
	int i, j = 0;
	struct NArray_node *temp;
	char fName[50], fType[5];
	while(*(fileName + j) != '.' && *(fileName + j)) { //split fileName and fileType from full FileName
			fName[j] = *(fileName + j);
			j++;
	}	
	copyString (fType, (fileName + j + 1));
	validateDirPath(dirPath, fileName);
	strcat(dirPath, fileName);
	while (*(fileName + j)) {
		*(fileName + j) = '\0';
		j++;
	}
	for (i = 0; i < MAX_FD_SIZE; i++) {
		if(header -> freeList[i] == 0) {
			copyString(header -> fd[i].filePath, dirPath);
			copyString(header -> fd[i].fileName, fName);
			copyString(header -> fd[i].fileType, fType);
			copyString(header -> bl[i].data, data);
			header -> fd[i].size = getSize(data);
			header -> freeList[i] = 1;
			/*if(writeToFile(truncateLeft(dirPath, 4), data))
				puts(ERR_VFS_ADDFILE_01);*/
			return i;
		}
	}
	return -4;
}

int copyFile(char *srcFilePath, char *destFilePath, struct VFS *header, struct NArray_node *NArrayRoot, struct BST_node *BSTRoot, struct HashNode **table) {
	int i, l;
	struct NArray_node *temp;
	struct HashNode **temp2;
	temp = searchNArrayNode (NArrayRoot, srcFilePath);
	if (temp == NULL) 
		return 1;
	temp = searchNArrayNode (NArrayRoot, destFilePath);
	if (temp == NULL) 
		return 2;
	for (l = 0; l < MAX_FD_SIZE; l++)
		if(header -> freeList[l] == 1)
			if(!strcmp(header -> fd[l].filePath, srcFilePath))
				break;
	if (l == MAX_FD_SIZE)
		return 3;
	for (i = 0; i < MAX_FD_SIZE; i++) {
		if(header -> freeList[i] == 0) {
			copyString(header -> fd[i].filePath, destFilePath);
			copyString(header -> fd[i].fileName, header -> fd[l].fileName);
			copyString(header -> fd[i].fileType, header -> fd[l].fileType);
			header -> fd[i].size = header -> fd[l].size;
			copyString(header -> bl[i].data, header -> bl[l].data);
			header -> fd[i].size = header -> fd[l].size;
			header -> freeList[i] = 1;
			NArrayRoot = insertNArrayNode(NArrayRoot, destFilePath);
			BSTRoot = insertBSTNode(BSTRoot, destFilePath);
			temp2 = hash (header -> fd[i].fileName, table);
			*temp2 = addHashNode (&header -> fd[i], *temp2);
			/*if(writeToFile(truncateLeft(dirPath, 4), data))
				puts(ERR_VFS_ADDFILE_01);*/
			return 0;
		}
	}
	return 4;
}
